//
//  LJFSearchController.m
//  SevenZhou
//
//  Created by qianfeng on 15/9/14.
//  Copyright (c) 2015年 ljf. All rights reserved.
//

#import "LJFSearchController.h"
#import "LJFSearchCell.h"
#import "LJFHttpManager.h"
#import "LJFHotSearchModel.h"
#import "LJFHotCell.h"
#import "LJFDetailController.h"
#import "LJFSearchResultController.h"
#import "LJFCustomController.h"
#import "LJFFMDBManager.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"


@interface LJFSearchController ()<UITableViewDataSource,UITableViewDelegate,LJFHotCellDelegate,UITextFieldDelegate,MJRefreshBaseViewDelegate>
{
    NSMutableArray *_dataArr;
    
    NSArray *_keyArr;
    
    NSMutableArray *_recordArr;
    
    MBProgressHUD *_HUD;
    
    MJRefreshHeaderView *_refresHeadView;
    
    BOOL _isRefresh;
}

@property (weak, nonatomic) IBOutlet UITableView *myTableView;

@property (weak, nonatomic) IBOutlet UITextField *searchText;

@property (weak, nonatomic) IBOutlet UIButton *backButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *letfContrant;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomcontrant;

@end

@implementation LJFSearchController

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self)
    {
        _dataArr = [[NSMutableArray alloc] init];
        _recordArr = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self showProgress];
    
    [self createRefreshView];
    
    [self setSearchTextLeftMagin];
    
    [self isfirstpush];
    
    [self loadDataFromNet];
    
    [self loadRecordDatafromDB];
}

- (void)showProgress
{
    _HUD = [[MBProgressHUD alloc] initWithView:self.view];
    _HUD.labelText = @"正在努力加载中";
    
    [self.view addSubview:_HUD];
    
    [_HUD show:YES];
    
}

- (void)createRefreshView
{
    _refresHeadView = [[MJRefreshHeaderView alloc] init];
    _refresHeadView.scrollView = _myTableView;
    _refresHeadView.delegate = self;
}

- (void)dealloc
{
    [_refresHeadView free];
}

- (void)setSearchTextLeftMagin
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 1)];
    self.searchText.leftView = view;
    self.searchText.leftViewMode = UITextFieldViewModeAlways;
}

- (void)loadRecordDatafromDB
{
    LJFFMDBManager *manager = [LJFFMDBManager shareInstance];
    
    FMResultSet *rs = [manager selectFromTableName:@"rsearchRecord"];
    
    while ([rs next])
    {
        NSString *name = [rs stringForColumn:@"name"];
        
        [_recordArr addObject:name];
    }
    
    [_myTableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadDataFromNet
{
    LJFHttpManager *manager = [LJFHttpManager shareInstance];
    
    [manager getDataFromNetWithUrl:URL_HotSearch AndParameterStr:@"" success:^(id responseObj)
    {
        if (_isRefresh)
        {
            _isRefresh = NO;
            [_dataArr removeAllObjects];
        }
        
        NSString *key_string = responseObj[@"data"][@"hot_keyword"];
        
        NSArray *arr = [key_string componentsSeparatedByString:@","];
        
        _keyArr = [NSArray arrayWithArray:arr];
        
        for (NSDictionary *dict in responseObj[@"data"][@"recommend"])
        {
            LJFHotSearchModel *model = [[LJFHotSearchModel alloc] init];
            model.goods_id = dict[@"goods_id"];
            model.goods_name = dict[@"goods_name"];
            
            [_dataArr addObject:model];
        }
        
        [_HUD hide:YES];
        
        [_myTableView reloadData];
        
        [_refresHeadView endRefreshing];
        
    } failure:^(NSError *error)
    {
        
        NSLog(@"error == %@",error);
        
    }];
}

- (void)myhidden
{
    self.backButton.hidden = YES;
    
    self.letfContrant.constant = 5;
    self.bottomcontrant.constant = 49;
    
    LJFCustomController *tabar = (LJFCustomController *)self.tabBarController;
    tabar.tabBarView.hidden = NO;
}

- (void)myshow
{
    self.backButton.hidden = NO;
    
    self.letfContrant.constant = 21;
    self.bottomcontrant.constant = 0;
    
    LJFCustomController *tabar = (LJFCustomController *)self.tabBarController;
    tabar.tabBarView.hidden = YES;
}

- (void)isfirstpush
{
    if (_isFristPush)
    {
        [self myshow];
    }
    else
    {
        [self myhidden];
    }
}

- (IBAction)beginSearch:(id)sender
{
    [self.view endEditing:YES];
    
    if (_searchText.text.length == 0)
    {
        return;
    }
    
    [self insertDataWithKeyword:_searchText.text];
    
    [self searchWithKeywords:self.searchText.text];
}

- (void)insertDataWithKeyword:(NSString *)keyword
{
    LJFFMDBManager *manager = [LJFFMDBManager shareInstance];
    
    [manager creatTableOfDataBaseWithTableName:@"rsearchRecord" dictionary:@{@"name":@"text"}];
    
    FMResultSet *rs = [manager selectFromTableName:@"rsearchRecord"];
    
    NSMutableArray *arrM = [[NSMutableArray alloc] init];
    
    while ([rs next])
    {
        NSString *name = [rs stringForColumn:@"name"];
        
        [arrM addObject:name];
    }
    
    if (![arrM containsObject:keyword])
    {
        if (![manager.dataBase executeUpdate:@"insert into rsearchRecord(name) values(?)",keyword])
        {
            NSLog(@"插入失败");
        }
    }
    
    [_recordArr removeAllObjects];
    
    [self loadRecordDatafromDB];
}

- (IBAction)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
    [self myhidden];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (_isFristPush)
    {
        [self myshow];
        
        [self.searchText becomeFirstResponder];
    }
}

- (void)searchWithKeywords:(NSString *)keywords;
{
    LJFSearchResultController *searchResult = [self.storyboard instantiateViewControllerWithIdentifier:@"LJFSearchResultController"];
    searchResult.keywords = keywords;
    searchResult.sort_by = @"top_sale";
    
    [self.navigationController pushViewController:searchResult animated:YES];
}

- (void)clearRecord:(UIButton *)button
{
    LJFFMDBManager *manager = [LJFFMDBManager shareInstance];
    
    [manager deleteTableDataOfDBWithName:@"rsearchRecord"];
    
    [_recordArr removeAllObjects];
    
    [self loadRecordDatafromDB];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -MJRefreshBaseViewDelegate

-(void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    _isRefresh = YES;
    
    [self loadDataFromNet];
}

#pragma mark -UITableViewDataSource,UITableViewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section ==2)
    {
        return _dataArr.count;
    }
    else if (section == 1)
    {
        return _recordArr.count;
    }
    else
    {
        return 1;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        LJFHotCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LJFHotCell"];
        cell.mydeletage = self;
        
        cell.array = _keyArr;
        
        return cell;
    }
    else if (indexPath.section == 1)
    {
        LJFHotCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LJFHotCell"];
        cell.mydeletage = self;
        
        cell.recordArr = _recordArr;
        
        return cell;

    }
    else
    {
        LJFHotSearchModel *model = _dataArr[indexPath.row];
        
        LJFSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LJFSearchCell"];
        
        cell.nameTitle.text = model.goods_name;
        
        return cell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    
    UIImageView *bgView = [[UIImageView alloc] initWithFrame:view.bounds];
    bgView.image = [UIImage imageNamed:@"cell_bg_content.png"];
    [view addSubview:bgView];
        
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 6, 30, 30)];
    [view addSubview:imageView];
        
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(45, 6, 100, 30)];
    label.font = [UIFont systemFontOfSize:17];
    [view addSubview:label];
        
    if (section == 0)
    {
        imageView.image = [UIImage imageNamed:@"ic_action_search_eye"];
        label.text = @"热门搜索";
    }
    else if(section == 1)
    {
        imageView.image = [UIImage imageNamed:@"ic_action_time"];
        label.text = @"历史记录";
    }
    else
    {
        imageView.image = [UIImage imageNamed:@"ic_action_recommendation.png"];
        label.text = @"热门推荐";
    }
        
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
     UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame =CGRectMake(0, 0, self.view.frame.size.width, 30);
    [button setTitle:@"清除历史记录" forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"cell_bg_content.png"] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clearRecord:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    if (section == 1 && _recordArr.count != 0)
    {
         button.hidden = NO;
    }
    else
    {
        button.hidden = YES;
    }
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 1)
    {
        return 100;
    }
    else
    {
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 30;
        
    }else if(section == 1)
    {
        if (_recordArr.count == 0)
        {
            return 30;
        }
        else
        {
             return 74;
        }
    }
    else
    {
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 2)
    {

        LJFHotSearchModel *model = _dataArr[indexPath.row];
        
        LJFDetailController *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"LJFDetailController"];
        detail.goodsid = model.goods_id;
        
        [self.navigationController pushViewController:detail animated:YES];
    }
}

#pragma mark -LJFHotCellDelegate

- (void)LJFHotCell:(LJFHotCell *)cell andSearchKeyStringTag:(NSInteger)tag
{
    [self.view endEditing:YES];
    
    NSString *keyName = _keyArr[tag];
    
    [self searchWithKeywords:keyName];
}

- (void)LJFHotCell:(LJFHotCell *)cell andSearchRecordTag:(NSInteger)tag
{
    [self.view endEditing:YES];
    
    NSString *keyName = _recordArr[tag];
    
    [self searchWithKeywords:keyName];
}

#pragma mark -UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    [self searchWithKeywords:textField.text];
    
    return YES;
}


@end
